angular.module('Caltech').controller('configController', function ($scope, Restangular, Areas, Constants) {
    'use strict';
    $scope.areas = Areas;
    $scope.user = Constants.accountInfo;

    Restangular.all('role').getList().then(function (roles) {
        $scope.roles = roles.map(function (role) {
            var areas = [];

            if (role.areas > 0) {
                $scope.areas.forEach(function (area) {
                    if (role.areasText.indexOf(area.text) >= 0) {
                        areas.push(area.value);
                    }
                });
            }

            role.areaItems = areas;

            return role;
        });
    });

    $scope.updateRole = function (role) {

        role.areas = role.areaItems.reduce(function (prev, value) {
            var num = parseInt(value, 10);
            return prev + num;
        }, 0);

        return role.put();
    };

    $scope.selectionOptions = {
        multiple: true,
        containerCssClass: 'form-control'
    };
});